﻿#include "StdAfx.h"
#include "UIDlgBuilder.h"

CControlUI* CDialogBuilder::Create(LPCTSTR pstrXML) {
	if (!m_xml.Load(pstrXML)) {
		return NULL;
	}
	// NOTE: The root element is actually discarded since the _Parse() methods is
	//       parsing children and attaching to the current node.
	CMarkupNode root = m_xml.GetRoot();
	return _Parse(&root);
}

CControlUI* CDialogBuilder::_Parse(CMarkupNode* pRoot, CControlUI* pParent) {
	IContainerUI* pContainer = NULL;
	CControlUI* pReturn = NULL;
	for ( CMarkupNode node = pRoot->GetChild() ; node.IsValid(); node = node.GetSibling() ) {
		LPCTSTR pstrClass = node.GetName(); // 获取标签LabelPanel
		SIZE_T cchLen = _tcslen(pstrClass); // 标签的长度10个字符
		CControlUI* pControl = NULL;
		switch ( cchLen ) {
		case 6:
			if (_tcscmp(pstrClass, _T("Button")) == 0) {
				pControl = new CButtonUI;
			}
			break;
		case 9:
			if (_tcscmp(pstrClass, _T("TextPanel")) == 0) {
				pControl = new CTextPanelUI;
			}
			break;
		case 10:
			if (_tcscmp(pstrClass, _T("LabelPanel")) == 0) {
				pControl = new CLabelPanelUI;
			}
			break;
		case 12:
			if (_tcscmp(pstrClass, _T("DialogLayout")) == 0) {
				pControl = new CDialogLayoutUI;
			}
			break;
		}
		ASSERT(pControl);
		if (pControl == NULL) {
			return NULL;
		}
		// Add children
		if ( node.HasChildren() ) {
			_Parse(&node, pControl);
		}
		// Attach to parent
		if (pParent != NULL) {
			if (pContainer == NULL) pContainer = static_cast<IContainerUI*>(pParent->GetInterface(_T("Container")));
			ASSERT(pContainer);
			if (pContainer == NULL) return NULL;
			pContainer->Add(pControl);
		}
		// Process attributes
		if ( node.HasAttributes() ) {
			TCHAR szValue[500] = { 0 };
			SIZE_T cchLen = lengthof(szValue) - 1;
			// Set ordinary attributes
			int nAttributes = node.GetAttributeCount();
			for ( int i = 0; i < nAttributes; i++ ) {
				pControl->SetAttribute(node.GetAttributeName(i), node.GetAttributeValue(i));
			}
		}
		// Return first item
		if (pReturn == NULL) {
			pReturn = pControl;
		}
	}
	return pReturn;
}
